package cn.melonlib.cores.commons.model.support;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.melonlib.cores.commons.comp.MelonLibSystemConfig;
import cn.melonlib.cores.commons.comp.utils.ApplicationContextUtils;
import cn.melonlib.cores.commons.model.anno.MelonEntityId;
import cn.melonlib.cores.commons.model.entity.IEntity;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.springframework.core.annotation.AnnotationUtils;

import java.io.Serializable;

public class MelonLibIdGenerator implements IdentifierGenerator {
    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        long workId=1L;
        long dataId=1L;
        String systemName="TEST";
        try {
            MelonLibSystemConfig systemConfig = ApplicationContextUtils.getApplicationContext().getBean(MelonLibSystemConfig.class);
            workId=NumberUtil.parseLong(systemConfig.getWorkerId());
            dataId=NumberUtil.parseLong(systemConfig.getDataId());
            systemName=systemConfig.getSystemName();
        }catch (Exception e){

        }

        if(o instanceof IEntity){
            MelonEntityId melonEntityId=AnnotationUtils.findAnnotation(o.getClass(), MelonEntityId.class);
            if(melonEntityId==null){
                return IdUtil.fastSimpleUUID();
            }
            switch (melonEntityId.type()){
                case UUID:return systemName+"_"+workId+"_"+dataId+"_"+IdUtil.randomUUID();
                case FAST_UUID:return systemName+"_"+workId+"_"+dataId+"_"+IdUtil.fastSimpleUUID();
                case SNOW_FLAKE:{
                    switch (melonEntityId.IdValueType()){
                        case STRING:
                            return String.valueOf(IdUtil.getSnowflake(workId,dataId).nextId());
                        default:return IdUtil.getSnowflake(workId,dataId).nextId();
                    }
                }
                default:IdUtil.fastSimpleUUID();
            }
        }else{
            throw new HibernateException("不是可持久化的ID对象");
        }
        return IdUtil.fastSimpleUUID();
    }
}
